package top.superxuqc.loginbili.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.superxuqc.loginbili.util.RSA;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {


    private RestTemplate rest = new RestTemplate();


    public Map<String,String> solveNoAI(){
        HashMap<String,String> map = new HashMap<>();
        String result = rest.getForObject("http://passport.bilibili.com/web/captcha/combine?plat=6", String.class);
        JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data").getJSONObject("result");
        String gt = jsonObject.get("gt").toString();
        String challenge = jsonObject.get("challenge").toString();
        String key = jsonObject.get("key").toString();
        System.out.println(gt);
        System.out.println(challenge);
        System.out.println(key);
        map.put("gt",gt);
        map.put("challenge",challenge);
        map.put("key",key);
        return map;
    }

    public String solveRSA(){

        String result = rest.getForObject("http://passport.bilibili.com/login?act=getkey", String.class);




        return result;

    }

    public void set(HttpServletResponse response,
                           org.apache.commons.httpclient.Cookie[] cookies) {
        Date date = new Date();
        long startTime = date.getTime();
        long endTime = cookies[0].getExpiryDate().getTime();
        int maxAge = (int)((endTime-startTime)/1000);
        for (org.apache.commons.httpclient.Cookie c:cookies
             ) {
            Cookie cookie = new Cookie(c.getName(),c.getValue());
            cookie.setPath("/");

            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        }

    }
    public void set(HttpServletResponse response,
                    org.apache.commons.httpclient.Cookie[] cookies,Boolean b) {
        Date date = new Date();
        long startTime = date.getTime();
        long endTime = cookies[0].getExpiryDate().getTime();
        int maxAge = (int)((endTime-startTime)/1000);
        for (org.apache.commons.httpclient.Cookie c:cookies
        ) {
            Cookie cookie = new Cookie(c.getName(),c.getValue());
            cookie.setPath("/");

            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        }
        Cookie c = new Cookie("expireTime",endTime+"");
        c.setMaxAge(maxAge);
        response.addCookie(c);
    }

}
